package com.hrt.manage.role.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hrt.bean.Role;
import com.hrt.bean.UserRoles;
import com.hrt.manage.role.dao.UserRoleDao;
import com.hrt.manage.role.service.RoleService;
import com.hrt.manage.role.service.UserRoleService;

@Service
public class UserRoleServiceImpl implements UserRoleService {

	@Autowired
	private UserRoleDao userRoleDao;

	@Autowired
	private RoleService roleService;

	@Override
	public List<Role> queryRolesByUserId(Long userId) {
		// TODO Auto-generated method stub
		List<Role> roles = new ArrayList<Role>();
		roles = userRoleDao.queryRolesByUserId(userId);
		return roles;
	}

	@Override
	@Transactional
	public void saveRolesByUserId(Long userId, List<Long> roleList) {
		// TODO Auto-generated method stub
		List<Role> oldRoles = new ArrayList<Role>();
		List<Role> newRoles = new ArrayList<Role>();
		oldRoles = queryRolesByUserId(userId);

		if (!roleList.isEmpty()) {
			newRoles = roleService.getRoleByIds(roleList
					.toArray(new Long[roleList.size()]));

		}
		if (oldRoles != null && !oldRoles.isEmpty()) {
			deleteRolesByUserId(userId, oldRoles);
		}
		if (newRoles != null && !newRoles.isEmpty()) {
			if (newRoles != null && !newRoles.isEmpty()) {
				for (Role role : newRoles) {
					UserRoles ur = new UserRoles();
					ur.setIsdelete(0);
					ur.setRoleId(role.getId());
					ur.setrName(role.getrName());
					ur.setUserId(userId);
					userRoleDao.saveEntity(ur);
				}
			}
		}

	}

	@Transactional
	@Override
	public void deleteRolesByUserId(Long userId, List<Role> oldRoles) {
		if (oldRoles != null && !oldRoles.isEmpty()) {
			if (oldRoles != null && !oldRoles.isEmpty()) {
				for (Role role : oldRoles) {
					UserRoles ur =this.userRoleDao.getUserRoleById(userId, role.getId());
					if (ur != null) {
						userRoleDao.deleteEntity(ur.getId());
					}
				}
			}
		}

	}

}
